using Microsoft.EntityFrameworkCore;
using MediPlatform.Domain.Order;
using MediPlatform.Infeartructure;

namespace MediPlatform.Read.Api.Services
{
    public class ConsultationOrderDataInitializer
    {
        private readonly MyDbContext _context;
        private readonly ILogger<ConsultationOrderDataInitializer> _logger;

        public ConsultationOrderDataInitializer(MyDbContext context, ILogger<ConsultationOrderDataInitializer> logger)
        {
            _context = context;
            _logger = logger;
        }

        public async Task InitializeAsync()
        {
            try
            {
                _logger.LogInformation("开始初始化问诊单测试数据");

                // 检查是否已有数据
                if (await _context.ConsultationOrder.AnyAsync())
                {
                    _logger.LogInformation("问诊单数据已存在，跳过初始化");
                    return;
                }

                // 确保有用户数据
                await EnsureUsersExistAsync();

                // 创建问诊单数据
                await CreateConsultationOrdersAsync();

                // 创建问诊记录
                await CreateConsultationRecordsAsync();

                // 创建问诊评价
                await CreateConsultationReviewsAsync();

                await _context.SaveChangesAsync();

                _logger.LogInformation("问诊单测试数据初始化完成");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "初始化问诊单测试数据失败");
                throw;
            }
        }

        private async Task EnsureUsersExistAsync()
        {
            // 检查是否有足够的患者用户
            var patientCount = await _context.User.Where(u => u.Role == "patient").CountAsync();
            var doctorCount = await _context.User.Where(u => u.Role == "doctor").CountAsync();

            if (patientCount < 5 || doctorCount < 5)
            {
                var users = new List<User>();

                // 如果患者不足，添加患者
                if (patientCount < 5)
                {
                    for (int i = patientCount; i < 5; i++)
                    {
                        users.Add(new User 
                        { 
                            UserId = $"P{(i + 1):D3}", 
                            Username = $"患者{i + 1}", 
                            PhoneNumber = $"1380013800{i + 1}", 
                            PasswordHash = "hashed_password", 
                            Role = "patient" 
                        });
                    }
                }

                // 如果医生不足，添加医生
                if (doctorCount < 5)
                {
                    for (int i = doctorCount; i < 5; i++)
                    {
                        users.Add(new User 
                        { 
                            UserId = $"D{(i + 1):D3}", 
                            Username = $"医生{i + 1}", 
                            PhoneNumber = $"1390013900{i + 1}", 
                            PasswordHash = "hashed_password", 
                            Role = "doctor" 
                        });
                    }
                }

                if (users.Any())
                {
                    _context.User.AddRange(users);
                    await _context.SaveChangesAsync();
                    _logger.LogInformation("已添加 {Count} 个用户", users.Count);
                }
            }
        }

        private async Task CreateConsultationOrdersAsync()
        {
            var patients = await _context.User.Where(u => u.Role == "patient").ToListAsync();
            var doctors = await _context.User.Where(u => u.Role == "doctor").ToListAsync();

            // 检查是否有足够的数据
            if (patients.Count < 5 || doctors.Count < 5)
            {
                _logger.LogWarning("数据不足，无法创建问诊单。需要至少5个患者和5个医生。");
                return;
            }

            var random = new Random();
            var orders = new List<ConsultationOrder>();

            // 生成50条问诊单数据，每个状态大约10条
            for (int i = 1; i <= 50; i++)
            {
                var patient = patients[random.Next(patients.Count)];
                var doctor = doctors[random.Next(doctors.Count)];
                var consultationType = random.Next(1, 6); // 1-5
                var status = (i - 1) / 10; // 0-4，每个状态10条
                var submitTime = DateTime.Now.AddDays(-random.Next(1, 31)); // 最近30天内
                var fee = GetFeeByType(consultationType);

                var order = new ConsultationOrder
                {
                    OrderNo = $"CO{DateTime.Now:yyyyMMdd}{i:D3}",
                    PatientId = patient.Id,
                    DoctorId = doctor.Id,
                    HospitalId = random.Next(1, 6),
                    DepartmentId = random.Next(1, 11),
                    ConsultationType = consultationType,
                    Status = status,
                    SubmitTime = submitTime,
                    Fee = fee,
                    DiscountAmount = random.Next(0, (int)(fee * 0.2m)), // 0-20%的优惠
                    ActualPayment = fee,
                    CreatedAt = submitTime,
                    UpdatedAt = submitTime
                };

                // 根据状态设置其他字段
                if (status >= 1) // 进行中、已完成、已取消、已退诊
                {
                    order.PaymentMethod = GetRandomPaymentMethod();
                    order.PaymentTime = submitTime.AddMinutes(random.Next(5, 30));
                    order.ActualPayment = fee - (order.DiscountAmount ?? 0);
                }

                if (status == 1) // 进行中
                {
                    order.AppointmentTime = submitTime.AddHours(random.Next(1, 24));
                }

                if (status == 2) // 已完成
                {
                    order.AppointmentTime = submitTime.AddHours(random.Next(1, 24));
                }

                if (status == 3) // 已取消
                {
                    order.CancelReason = GetRandomCancelReason();
                }

                if (status == 4) // 已退诊
                {
                    order.RefundAmount = order.ActualPayment;
                    order.RefundTime = submitTime.AddDays(random.Next(1, 7));
                    order.CancelReason = GetRandomRefundReason();
                }

                orders.Add(order);
            }

            _context.ConsultationOrder.AddRange(orders);
            await _context.SaveChangesAsync();
            _logger.LogInformation("已创建 {Count} 条问诊单数据", orders.Count);
        }

        private async Task CreateConsultationRecordsAsync()
        {
            var orders = await _context.ConsultationOrder.Where(co => co.Status >= 1).ToListAsync();
            var records = new List<ConsultationRecord>();

            foreach (var order in orders)
            {
                var record = new ConsultationRecord
                {
                    OrderId = order.Id,
                    Symptoms = GetRandomSymptoms(),
                    MedicalHistory = GetRandomMedicalHistory(),
                    Diagnosis = GetRandomDiagnosis(),
                    TreatmentAdvice = GetRandomTreatmentAdvice(),
                    Duration = new Random().Next(300, 1800), // 5-30分钟
                    CreatedAt = order.SubmitTime?.AddMinutes(new Random().Next(5, 30))
                };

                records.Add(record);
            }

            _context.ConsultationRecord.AddRange(records);
            await _context.SaveChangesAsync();
            _logger.LogInformation("已创建 {Count} 条问诊记录", records.Count);
        }

        private async Task CreateConsultationReviewsAsync()
        {
            var orders = await _context.ConsultationOrder.Where(co => co.Status == 2).ToListAsync(); // 已完成的问诊
            var reviews = new List<ConsultationReview>();

            foreach (var order in orders)
            {
                var random = new Random();
                var review = new ConsultationReview
                {
                    OrderId = order.Id,
                    PatientId = order.PatientId,
                    DoctorId = order.DoctorId,
                    Rating = random.Next(3, 6), // 3-5星
                    Comment = GetRandomReviewComment(),
                    CreatedAt = order.SubmitTime?.AddHours(random.Next(1, 24))
                };

                reviews.Add(review);
            }

            _context.ConsultationReview.AddRange(reviews);
            await _context.SaveChangesAsync();
            _logger.LogInformation("已创建 {Count} 条问诊评价", reviews.Count);
        }

        private static decimal GetFeeByType(int consultationType)
        {
            return consultationType switch
            {
                1 => 50m, // 视频问诊
                2 => 30m, // 电话问诊
                3 => 30m, // 图文问诊
                4 => 40m, // 极速电话
                5 => 60m, // 复诊开药
                _ => 30m
            };
        }

        private static string GetRandomPaymentMethod()
        {
            var methods = new[] { "wechat", "alipay", "bank_card" };
            return methods[new Random().Next(methods.Length)];
        }

        private static string GetRandomCancelReason()
        {
            var reasons = new[]
            {
                "患者临时有事，取消问诊",
                "医生临时有事，取消问诊",
                "患者选择其他医生",
                "患者病情好转，不需要问诊",
                "系统故障，取消问诊"
            };
            return reasons[new Random().Next(reasons.Length)];
        }

        private static string GetRandomRefundReason()
        {
            var reasons = new[]
            {
                "医生无法及时接诊，申请退款",
                "患者对服务不满意，申请退款",
                "问诊质量不符合预期，申请退款",
                "系统问题导致问诊中断，申请退款",
                "患者病情需要线下就医，申请退款"
            };
            return reasons[new Random().Next(reasons.Length)];
        }

        private static string GetRandomSymptoms()
        {
            var symptoms = new[]
            {
                "头痛、发热、咳嗽",
                "腹痛、恶心、呕吐",
                "关节疼痛、肿胀",
                "皮肤瘙痒、红肿",
                "失眠、焦虑、抑郁",
                "胸闷、气短、心悸",
                "腰痛、下肢麻木",
                "视力模糊、眼痛",
                "耳鸣、听力下降",
                "食欲不振、体重下降"
            };
            return symptoms[new Random().Next(symptoms.Length)];
        }

        private static string GetRandomMedicalHistory()
        {
            var histories = new[]
            {
                "无特殊病史",
                "高血压病史3年",
                "糖尿病病史5年",
                "心脏病病史2年",
                "过敏史：青霉素过敏",
                "手术史：阑尾切除术",
                "家族史：父亲有高血压",
                "无慢性病史",
                "哮喘病史10年",
                "甲状腺功能亢进病史1年"
            };
            return histories[new Random().Next(histories.Length)];
        }

        private static string GetRandomDiagnosis()
        {
            var diagnoses = new[]
            {
                "上呼吸道感染",
                "急性胃肠炎",
                "骨关节炎",
                "过敏性皮炎",
                "焦虑症",
                "冠心病",
                "腰椎间盘突出",
                "结膜炎",
                "神经性耳鸣",
                "功能性消化不良"
            };
            return diagnoses[new Random().Next(diagnoses.Length)];
        }

        private static string GetRandomTreatmentAdvice()
        {
            var advices = new[]
            {
                "建议多休息，多喝水，必要时服用退烧药",
                "建议清淡饮食，避免辛辣刺激食物",
                "建议适当运动，避免剧烈运动",
                "建议避免接触过敏原，使用抗过敏药物",
                "建议保持良好心态，必要时寻求心理咨询",
                "建议规律作息，避免熬夜，定期复查",
                "建议卧床休息，避免久坐，必要时物理治疗",
                "建议保持眼部卫生，使用眼药水",
                "建议避免噪音环境，保持充足睡眠",
                "建议规律饮食，避免暴饮暴食"
            };
            return advices[new Random().Next(advices.Length)];
        }

        private static string GetRandomReviewComment()
        {
            var comments = new[]
            {
                "医生很专业，态度也很好",
                "问诊很详细，解答很耐心",
                "治疗效果不错，症状有所缓解",
                "医生经验丰富，诊断准确",
                "服务很周到，很满意",
                "医生很负责任，很专业",
                "问诊过程很顺利，很满意",
                "医生很细心，很专业",
                "治疗效果很好，推荐",
                "医生很耐心，很专业"
            };
            return comments[new Random().Next(comments.Length)];
        }
    }
} 